//
// Created by NH55 on 2021/5/29.
//

#include "testFile.h"

void readFile();

void writeFile();

void openFile(char *path, char *mode, void (*listener)(FILE *fp));

void readFile2(FILE *fp) {
    char buffer[512];

    fseek (fp, 0, SEEK_END); // 将文件指针移动到末尾

    char *fragment = (char *) calloc(ftell (fp) , sizeof(char));

    rewind(fp);

    printf ("0: %ld %s\n",ftell (fp) ,fragment); // 进行打印

    fscanf(fp, "%s", buffer);
    printf("1: %s  %lld  bytes = %ld \n", buffer , strlen(buffer)  ,ftell (fp));

    strcpy(fragment, buffer);
    printf("11: %s %lld\n", fragment, strlen(buffer));

    fgets(buffer, 512, (FILE *) fp);
    printf("2: %s  %lld  bytes = %ld \n", buffer , strlen(buffer) ,ftell (fp));

    strcat(fragment, buffer);
    printf("21: %s %lld\n", fragment, strlen(buffer));

    fgets(buffer, 255, (FILE*)fp);
    printf("3: %s bytes = %ld\n", buffer  ,ftell (fp));

    strcat(fragment, buffer);
    printf("31: %s %lld\n", fragment, strlen(buffer));

    printf("4:\n" );

    free(fragment) ;
}

void readFile3(FILE *fp) {
    char buffer[512];
    fseek (fp, 0, SEEK_END); // 将文件指针移动到末尾
    char *fragment = (char *) calloc(ftell (fp) , sizeof(char));
    // 重置文件指针
    rewind(fp);
    while (fgets(buffer, 512, (FILE *) fp)){
        strcat(fragment, buffer);
    }
    printf ("%ld\n%s\n",ftell (fp) ,fragment); // 进行打印
    free(fragment) ;
}

void studyFile() {
    //readFile();
    //writeFile() ;
    openFile("D:\\cppApp\\clion\\openglc\\shader\\test\\test_read.txt", "rb", readFile3);
}

void readFile() {
    printf("\n--> test : start > read file and printf to screen \n");
    FILE *vertex_file = NULL;
    vertex_file = fopen("D:\\cppApp\\clion\\openglc\\shader\\base_vertex.shader", "rb");
    if (!vertex_file) {
        printf("open file error \n");
        return;
    }
    int ch;
    while ((ch = getc(vertex_file)) != EOF) {
        putchar(ch);
    }
    fclose(vertex_file);
    printf("\n--< test : end  \n");
}

void writeFile() {
    FILE *fp = NULL;
    if ((fp = fopen("D:\\cppApp\\clion\\openglc\\shader\\test\\test.txt", "w+")) == NULL) {
        printf("open file error \n");
        return;
    }
    fprintf(fp, "This is testing for fprintf...\n");
    fputs("This is testing for fputs...\n", fp);
    fclose(fp);
}


void openFile(char *path, char *mode, void (*listener)(FILE *fp)) {
    FILE *fp = NULL;
    if ((fp = fopen(path, mode)) == NULL) {
        return;
    }
    if (listener) {
        listener(fp);
    }
    fclose(fp);
}
